package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.CheckGroupDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.CheckGroup;
import com.itheima.service.CheckGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service(interfaceClass = CheckGroupService.class)
@Transactional
public class CheckGroupServiceImpl implements CheckGroupService {

    @Autowired
    private CheckGroupDao checkGroupDao;

    /**
     * 分页条件查询
     *
     * @param queryPageBean
     * @return
     */
    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        Page<CheckGroup> page = checkGroupDao.selectByCondition(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 添加检查项
     *
     * @param checkGroup
     * @param checkitemIds
     */
    @Override
    public void add(CheckGroup checkGroup, Integer[] checkitemIds) {

        //1.先添加检查组，往t_checkgroup中添加一条数据
        checkGroupDao.add(checkGroup);
        //2.再添加检查组和检查项的关联信息，往t_checkgroup_checkitem添加多条数据
        for (Integer checkitemId : checkitemIds) {
            checkGroupDao.setCheckGroupAndCheckItem(checkGroup.getId(), checkitemId);
        }
    }

    /**
     * 根据检查组ID查询检查项ID集合
     * @param checkGroupId
     * @return
     */
    @Override
    public List<Integer> findCheckItemIdsByCheckGroupId(Integer checkGroupId) {
        return checkGroupDao.findCheckItemIdsByCheckGroupId(checkGroupId);
    }

    @Override
    public void edit(CheckGroup checkGroup, Integer[] checkitemIds) {
        //1.先添加检查组，往t_checkgroup中添加一条数据
        checkGroupDao.edit(checkGroup);

        //解除检查组和检查项的所有关联信息
        checkGroupDao.deleteAssocication(checkGroup.getId());

        //2.再添加检查组和检查项的关联信息，往t_checkgroup_checkitem添加多条数据
        for (Integer checkitemId : checkitemIds) {
            checkGroupDao.setCheckGroupAndCheckItem(checkGroup.getId(), checkitemId);
        }
    }

    @Override
    public List<CheckGroup> findAll() {
        return checkGroupDao.findAll();
    }
}
